package com.jbit.hxy.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jbit.hxy.common.Result;
import com.jbit.hxy.feign.UserFeignClient;
import com.jbit.hxy.model.dto.WxOrderDTO;
import com.jbit.hxy.model.dto.WxOrderDetailsDTO;
import com.jbit.hxy.model.po.WxOrder;
import com.jbit.hxy.model.po.WxOrderDetail;
import com.jbit.hxy.model.po.WxUser;
import com.jbit.hxy.service.order.WxOrderDetailService;
import com.jbit.hxy.service.order.WxOrderService;
import com.jbit.hxy.service.user.WxUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/order")
@RequiredArgsConstructor
@Tag(name = "订单服务")
public class OrderController {
    @Resource
    private WxOrderService wxOrderService;

    @Resource
    private WxOrderDetailService wxOrderDetailService;
    @Resource
    private UserFeignClient userFeignClient;


    /*
       创建订单
       下单：  下单用户、【购买菜品、购买数量、小计等等（订单明细）】、总金额、下单时间、生成订单流水号等等
     */

    // 下单功能，同时往订单表和订单明细表插入订单相关数据


    @PostMapping("/create")
    public Result createOrder(@RequestBody WxOrderDTO dto){
//        String openid = dto.getOpenid();
//        Result<WxUser> userByOpenId = userFeignClient.getUserByOpenId(openid);
//        WxUser wxUser = userByOpenId.getData();
        WxOrder wxOrder = new WxOrder();
        String number = generateOrderNo();
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        String orderSn = snowflake.nextIdStr();
        wxOrder.setNumber(orderSn);
        wxOrder.setAmount(dto.getAmount());
        wxOrder.setOpenid(dto.getOpenid());
        wxOrder.setStatus(1);
        wxOrder.setOrderTime(LocalDateTime.now());

//        wxOrder.setPhone(wxUser.getPhoneNumber());
//        wxOrder.setConsignee(wxUser.getNickName());
        wxOrder.setAddressId(dto.getAddressId());
        wxOrder.setRemark(dto.getRemark());
        wxOrderService.save(wxOrder);
        Long id = wxOrder.getId();
        List<WxOrderDetailsDTO> orderDetails = dto.getOrderDetails();
        for (WxOrderDetailsDTO orderDetail : orderDetails) {
            WxOrderDetail wxOrderDetail = new WxOrderDetail();
            wxOrderDetail.setOrderId(id);
            wxOrderDetail.setName(orderDetail.getName());
            wxOrderDetail.setImage(orderDetail.getImage());
            wxOrderDetail.setDishId(orderDetail.getDishId());
            wxOrderDetail.setSetmealId(orderDetail.getSetmealId());
            wxOrderDetail.setDishFlavor(orderDetail.getDishFlavor());
            wxOrderDetail.setQuantity(orderDetail.getQuantity());
            wxOrderDetail.setAmount(orderDetail.getSubtotal());
            wxOrderDetailService.save(wxOrderDetail);
        }
        return Result.success(wxOrder);
    }

    @GetMapping("/get")
    public Result<WxOrder> getOrderByOrderNumber(
            @RequestParam(value = "orderNumber") String orderNumber){
        LambdaQueryWrapper<WxOrder> whereCondition = Wrappers.lambdaQuery();
        whereCondition.eq(WxOrder::getNumber,orderNumber); // 订单号
        Optional<WxOrder> oneOpt = wxOrderService.getOneOpt(whereCondition);
        if(oneOpt.isPresent()){
            return Result.success(oneOpt.get());
        }else{
            return Result.fail("订单不存在");
        }
    }
    public String generateOrderNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String dateStr = sdf.format(new Date());
        int sequence = (int)(Math.random() * 1000); // 或者使用ThreadLocalRandom
        return dateStr + String.format("%03d", sequence);
    }


    @GetMapping("/list")
    @Operation(summary = "根据状态获取订单列表")
    public Result getOrderList(@RequestParam("openid") String openid, @RequestParam(value = "status",required = false) Integer status){
        switch (status){
            case 1:
                return Result.success(wxOrderService.getOrderByOpenidAndStatus(openid,status));
            case 3:
                return Result.success(wxOrderService.getOrderByOpenidAndStatus(openid,status));
            case 5:
                return Result.success(wxOrderService.getOrderByOpenidAndStatus(openid,status));
            case 6:
                return Result.success(wxOrderService.getOrderByOpenidAndStatus(openid,status));
            case 7:
                return Result.success(wxOrderService.getOrderByOpenidAndStatus(openid,status));
            default:
                return Result.success(wxOrderService.getOrderByOpenidAndStatus(openid,status));
        }

    }
    @GetMapping("/ChangeOrderStatus")
    @Operation(summary = "改变订单状态")
    public Result ChangeOrderStatus(@RequestParam("id") Integer id, @RequestParam("status") Integer status){
        WxOrder wxOrder = wxOrderService.getById(id);
        wxOrder.setStatus(status);
        wxOrderService.updateById(wxOrder);
        return Result.success(wxOrder);
    }
}
